/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.postp.postp_view.command;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.model.postp.PostpModel;
import br.ufmg.dees.insane.ui.rich.postp.postp_view.DesktopPostp;
import br.ufmg.dees.insane.ui.rich.postp.postp_view.InterfacePostp;
import br.ufmg.dees.insane.xyplot.xyplot_model.XYPlot;
import br.ufmg.dees.insane.xyplot.xyplot_view.InterfaceXYPlot;

/**
 * This class is a implementation of the interface Command.
 * its unabled to undo or redo.
 * its "execute" method verify the existence of a model, and
 * if that is one, it calls a file chooser to set the models name and
 * the save routine is called.
 *
 * @author Penna, Samuel & Fonseca, Flavio & Pitangueira, Roque
 * @since 05/07/2006
 * @see postp_view.command.Command
 */
public class SaveFileAsCommand implements Command {
    
    private DesktopPostp parent;
	private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter("ipp", "INSANE-POSTP Files");
	private boolean validFile;
    
//*****************************************************************************
	
    /**
     * Creates new SaveAsFileCommand
     * and sets the FileFilter to FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public SaveFileAsCommand(JFrame parent) {
        this.parent = (DesktopPostp)parent;
        fileChooser.setFileFilter(filter);
    }
    
//*****************************************************************************
	
    /**
     * Saves the current model accordding to ModelState name.
     * Prompts a dialog to choose another model name.
     *
     * @see gui.command.Command#execute()
     */
    public void execute() {
    	if(parent.getDesktop().getSelectedFrame() instanceof InterfacePostp){
    		if (((InterfacePostp)parent.getDesktop().getSelectedFrame()).getModel() != null) {
    			validFile = false;
    			while (!validFile) {
    				fileChooser.setCurrentDirectory(new File(((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath()));
    				fileChooser.setDialogTitle("Save as");
    				int retVal = fileChooser.showSaveDialog(parent);
    				if (retVal == JFileChooser.APPROVE_OPTION) {
    					
    					//Getting the file name
    					String s = fileChooser.getSelectedFile().getName();
    					
    					//Getting the file extension
    					String ext = new String();
    					int i = s.lastIndexOf('.');
    					if (i > 0 &&  i < s.length() - 1) {
    						ext = s.substring(i+1).toLowerCase();
    					}
    					
    					//Comparing the extension
    					if (!ext.equals("ipp")) {
    						s = s + ".ipp";
    						File file = fileChooser.getSelectedFile();
    						
    						//Changing the file in case of no good extensions
    						fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    					}
    					
    					//Checks if the file exists
    					if (fileChooser.getSelectedFile().exists()){
    						
    						if (((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath().equals(fileChooser.getSelectedFile().getPath())) {
    							validFile = true;
    						}
    						else {
    							int value = 10;
    							value = JOptionPane.showConfirmDialog(parent, 
    							"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
    							"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    							if (value == JOptionPane.YES_OPTION){
    								validFile = true;
    							}
    						}
    					}
    					else {
    						validFile = true;
    					}
    				}
    				else return;
    			}
    			if (((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName().equals("untitled.ipp"))
    				((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().setName(fileChooser.getSelectedFile().getName());
    			save();
    			
    		}
    	}else if(parent.getDesktop().getSelectedFrame() instanceof InterfaceXYPlot){
    		if (((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getModel() != null) {
    			validFile = false;
    			while (!validFile) {
    				fileChooser.setCurrentDirectory(new File(((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath()));
    				fileChooser.setDialogTitle("Save as");
    				int retVal = fileChooser.showSaveDialog(parent);
    				if (retVal == JFileChooser.APPROVE_OPTION) {
    					
    					//Getting the file name
    					String s = fileChooser.getSelectedFile().getName();
    					
    					//Getting the file extension
    					String ext = new String();
    					int i = s.lastIndexOf('.');
    					if (i > 0 &&  i < s.length() - 1) {
    						ext = s.substring(i+1).toLowerCase();
    					}
    					
    					//Comparing the extension
    					if (!ext.equals("ipp")) {
    						s = s + ".ipp";
    						File file = fileChooser.getSelectedFile();
    						
    						//Changing the file in case of no good extensions
    						fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    					}
    					
    					//Checks if the file exists
    					if (fileChooser.getSelectedFile().exists()){
    						
    						if (((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath().equals(fileChooser.getSelectedFile().getPath())) {
    							validFile = true;
    						}
    						else {
    							int value = 10;
    							value = JOptionPane.showConfirmDialog(parent, 
    							"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
    							"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    							if (value == JOptionPane.YES_OPTION){
    								validFile = true;
    							}
    						}
    					}
    					else {
    						validFile = true;
    					}
    				}
    				else return;
    			}
    			if (((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName().equals("untitled.ipp"))
    				((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().setName(fileChooser.getSelectedFile().getName());
    			save();
    			
    		}
    	}
    		
    
    
    
    
    
    
    
    
    }
    
//*****************************************************************************
	
    /**
     * Writes model on disc using a FileOutputStream and
     * an ObjectOutputStream.
     */
    private void save() {
    	if(parent.getDesktop().getSelectedFrame() instanceof InterfacePostp){
    		try{
                FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
                ObjectOutputStream stream = new ObjectOutputStream(serialStream);
                stream.writeObject((PostpModel)((InterfacePostp)parent.getDesktop().getSelectedFrame()).getPostpModel());
                serialStream.flush();
            }catch (Exception exc){
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(parent, "Couldn't save file!", "ERROR Message", JOptionPane.ERROR_MESSAGE);
            }
    	}else if(parent.getDesktop().getSelectedFrame()instanceof InterfaceXYPlot){
    		try{
                FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
                ObjectOutputStream stream = new ObjectOutputStream(serialStream);
                stream.writeObject((XYPlot)((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getModel());
                serialStream.flush();
            }catch (Exception exc){
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(parent, "Couldn't save file!", "ERROR Message", JOptionPane.ERROR_MESSAGE);
            }
    	}
    	
    }
    
//*****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//*****************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//*****************************************************************************
}

